package info.zlong.visibleruntime.log4j;

import com.alibaba.fastjson.JSON;
import info.zlong.visibleruntime.core.model.LogMsg;
import info.zlong.visibleruntime.core.mongo.MongoConnector;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

public class MongoDBAppender extends AppenderSkeleton {

	private String hosts;
	private String userName;
	private String password;
	private String databaseName;
	private String collectionName;
	private MongoConnector mongoConnector;
	

    public void activateOptions() {
		mongoConnector = new MongoConnector(hosts,userName,password, databaseName, collectionName);
    	mongoConnector.open();
    	super.activateOptions();
    }
    


    public void close() {
    	mongoConnector.close();
    }

    @Override
    protected void append(LoggingEvent event) {
		String msg = event.getRenderedMessage();
		try{
			LogMsg logMsg = JSON.parseObject(msg, LogMsg.class);
			mongoConnector.update(logMsg);
		}catch (Exception e) {
			LogLog.error("LogMsg存入Mongo出错:"+msg,e);
		}
    }

	public void setHosts(String hosts) {
		this.hosts = hosts;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}

	public void setCollectionName(String collectionName) {
		this.collectionName = collectionName;
	}



	public boolean requiresLayout() {
		return false;
	}



}
